<script setup lang="ts">
import type { Defect, StringNumberDictionary, LineEchartDataType } from '@/index.d';
import { useWindowSize } from '@vueuse/core';
import * as echarts from 'echarts';
const { width, height } = useWindowSize();
const props = defineProps({
  data: Array<Defect>,
  title: {
    validator(value: LineEchartDataType) {
      return ['testMethod', 'partType', 'makeMethod'].includes(value);
    }
  }
});

let container: HTMLDivElement;
let chartInstance: echarts.ECharts;
interface DataType {
  name: string;
  value: number;
}
const generateDataList = (
  lineEchartDataType: LineEchartDataType = props.title as LineEchartDataType,
  top: number = 5
): Array<DataType> => {
  const dataList: string[] = props.data?.map(element => element[lineEchartDataType]) as string[];
  const dataListUnique: string[] = dataList.filter(
    (item, index) => dataList.indexOf(item) === index
  );
  const valueList: StringNumberDictionary = {};
  dataListUnique.forEach(element => {
    valueList[element] = 0;
  });
  props.data?.forEach(element => {
    valueList[element[lineEchartDataType] as keyof typeof valueList]++;
  });
  const arrList: Array<DataType> = [];
  Object.keys(valueList).forEach(element => {
    arrList.push({
      name: element,
      value: valueList[element]
    });
  });
  arrList.sort((a, b) => b.value - a.value);
  return arrList.slice(0, top);
};

let pieOption: echarts.EChartsCoreOption;
let lineOption: echarts.EChartsOption;
let barOption: echarts.EChartsOption;

let index: number = 0;
const optionList: Array<echarts.EChartsOption | echarts.EChartsCoreOption> = [];
const makeOption = () => {
  const titleContent =
    props.title === 'partType'
      ? '工件类型'
      : props.title === 'testMethod'
        ? '检测方法'
        : '加工方法';

  const title = {
    show: true,
    text: titleContent + '-缺陷数量',
    left: 'center',
    textStyle: {
      fontSize: '14px',
      weight: 'normal'
    }
  };

  pieOption = {
    title,
    tooltip: {
      trigger: 'item'
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    legend: {
      bottom: '5%',
      left: 'center'
    },
    series: [
      {
        type: 'pie',
        radius: ['35%', '50%'],
        avoidLabelOverlap: false,
        padAngle: 5,
        itemStyle: {
          borderRadius: 10
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: generateDataList()
      }
    ]
  };

  lineOption = {
    title,
    legend: {
      top: '5%',
      left: 'center'
    },
    toolbox: {
      feature: {
        saveAsImage: {},
        dataView: {}
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    xAxis: {
      type: 'category',
      data: generateDataList().map(item => item.name)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: generateDataList().map(item => item.value),
        type: 'line'
      }
    ]
  };

  barOption = {
    title,
    legend: {
      top: '5%',
      left: 'center'
    },
    toolbox: {
      feature: {
        saveAsImage: {},
        dataView: {}
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    xAxis: {
      type: 'category',
      data: generateDataList().map(item => item.name)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: generateDataList().map(item => item.value),
        type: 'bar'
      }
    ]
  };
  optionList.push(pieOption);
  optionList.push(lineOption);
  optionList.push(barOption);
};

const initEChart = () => {
  if (props.data === undefined || props.data.length === 0 || props.title === undefined) {
    return;
  }
  makeOption();
  container = document.getElementById(props.title as string) as HTMLDivElement;
  chartInstance = echarts.init(container);
  chartInstance.setOption(optionList[index], true);
};

watch(
  () => props.data as Array<Defect>,
  () => initEChart()
);

setInterval(() => {
  chartInstance && chartInstance.setOption(optionList[index], true);
  index = index === optionList.length - 1 ? 0 : index + 1;
}, 10000);

watch(
  () => [width, height],
  () => chartInstance && chartInstance.resize(),
  {
    deep: true
  }
);
</script>
<template>
  <div :id="props.title as string" class="echart-container" />
</template>
<style scoped lang="scss">
.echart-container {
  width: 100%;
  height: 100%;
}
</style>
